from django.shortcuts import render, redirect, get_object_or_404
from django.contrib import messages
from core.models.course_period import CoursePeriod
from core.forms.course_period_form import CoursePeriodForm


def course_period_list(request):
    """
    课程时间段列表视图
    """
    course_periods = CoursePeriod.objects.all()
    return render(request, 'core/course_period/list.html', {
        'course_periods': course_periods
    })


def course_period_create(request):
    """
    创建课程时间段视图
    """
    if request.method == 'POST':
        form = CoursePeriodForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, '课程时间段创建成功！')
            return redirect('core:course_period_list')
    else:
        form = CoursePeriodForm()
    return render(request, 'core/course_period/form.html', {
        'form': form,
        'title': '创建课程时间段'
    })


def course_period_update(request, pk):
    """
    更新课程时间段视图
    """
    period = get_object_or_404(CoursePeriod, pk=pk)
    if request.method == 'POST':
        form = CoursePeriodForm(request.POST, instance=period)
        if form.is_valid():
            form.save()
            messages.success(request, '课程时间段更新成功！')
            return redirect('core:course_period_list')
    else:
        form = CoursePeriodForm(instance=period)
    return render(request, 'core/course_period/form.html', {
        'form': form,
        'title': '更新课程时间段'
    })


def course_period_delete(request, pk):
    """
    删除课程时间段视图
    """
    period = get_object_or_404(CoursePeriod, pk=pk)
    if request.method == 'POST':
        period.delete()
        messages.success(request, '课程时间段删除成功！')
        return redirect('core:course_period_list')
    return render(request, 'core/course_period/confirm_delete.html', {
        'period': period
    })